<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-form-item label="模块名称" prop="moduleName">
        <el-input
          v-model="queryParams.moduleName"
          placeholder="请输入模块名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="公司名称" prop="supplierName" v-if="showSupplier()">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入公司名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="模块标签" prop="moduleTag">
        <el-select
          v-model="queryParams.moduleTag"
          placeholder="模块标签"
          clearable
        >
          <el-option
            v-for="dict in dict.type.sys_supplier_module_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="moduleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="100"
        ><template slot-scope="scopes">
          {{ scopes.$index + 1 }}
        </template></el-table-column
      >
      <el-table-column
        label="名称"
        align="center"
        prop="moduleName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="模块标签"
        align="center"
        prop="moduleTag"
        width="100"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_supplier_module_type"
            :value="scope.row.moduleTag"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="showSupplier()"
        label="所属公司"
        align="center"
        prop="supplierName"
        width="400"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="toCompany(scope.row.supplierId)">{{
            scope.row.supplierName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="创建者"
        align="center"
        prop="createBy"
        width="100"
      />

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="createTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ judgeStatus(scope.row.moduleStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.moduleStatus == '2'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePublish(scope.row)"
            >发布</el-button
          >
          <el-button
            v-if="showSupplier() && scope.row.moduleStatus == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="
              () => {
                currentRow = scope.row;
                radio = undefined;
                reason = undefined;
                dialogVisible = true;
              }
            "
            >审核</el-button
          >
          <el-button
            v-if="scope.row.moduleStatus == '3'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUnuse(scope.row)"
            >下架</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="toProduct(scope.row.moduleId)"
            >查看</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="showSupplier()">
            <el-form-item label="所属服务商" prop="supplierId">
              <treeselect
                v-model="form.supplierId"
                :options="supplierOptions"
                :normalizer="normalizer"
                placeholder="所属服务商"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="所属模块" prop="moduleTag">
              <el-select
                v-model="form.moduleTag"
                placeholder="请选择模块标签"
                @change="changeModuleTag"
              >
                <el-option
                  v-for="dict in dict.type.sys_supplier_module_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="所属领域" prop="moduleTypeId">
              <el-cascader
                v-model="form.moduleTypeId"
                :options="moduleTypeOptions"
                :props="{
                  expandTrigger: 'hover',
                  checkStrictly: true,
                  value: 'id',
                }"
                :show-all-levels="false"
                placeholder="选择模块类型"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="nameForModule" prop="moduleName">
              <el-input
                v-model="form.moduleName"
                :placeholder="'请输入' + nameForModule"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面">
              <image-upload v-model="form.moduleLogo" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="介绍">
              <editor v-model="form.moduleIntro" :min-height="192" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <div style="margin-left: 10%">
        <el-radio v-model="radio" label="2">同意</el-radio>
        <el-radio v-model="radio" label="1">退回</el-radio>

        <div style="margin-top: 15px">
          <el-input
            v-if="radio == 1"
            v-model="reason"
            type="textarea"
            :rows="2"
            placeholder="请输入退回原因"
          >
          </el-input>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAudit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listModule,
  getModule,
  delModule,
  addModule,
  updateModule,
} from "@/api/system/module";

import { treeselectbyId } from "@/api/system/moduletypedomain";
import { listDept } from "@/api/system/dept";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Module",
  dicts: ["sys_module_status", "sys_supplier_module_type"],
  components: { Treeselect },

  data() {
    return {
      nameForModule: "模块名称",
      radio: undefined,
      reason: undefined,
      currentRow: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模块表格数据
      moduleList: [],
      // 模块类型树选项
      moduleTypeOptions: [],
      // 服务商树选项
      supplierOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        moduleName: undefined,
        createBy: undefined,
        status: undefined,
        supplierId: this.$store.state.user.roles.includes("admin")
          ? undefined
          : this.$store.state.user.compId,
      },
      dialogVisible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        supplierId: [
          { required: true, message: "所属服务商不能为空", trigger: "blur" },
        ],
        moduleTypeId: [
          { required: true, message: "模块类型不能为空", trigger: "blur" },
        ],
        moduleLogo: [
          { required: true, message: "模块logo不能为空", trigger: "blur" },
        ],
        moduleIntro: [
          { required: true, message: "模块介绍不能为空", trigger: "blur" },
        ],
        moduleName: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        moduleTag: [
          { required: true, message: "模块标签不能为空", trigger: "change" },
        ],
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    handlePublish(row) {
      row.moduleStatus = 3;
      updateModule(row).then((response) => {
        console.log(response, "response");
        this.$modal.msgSuccess("发布成功");

        this.getList();
      });
    },
    handleAudit() {
      console.log(this.currentRow);
      this.currentRow.moduleStatus = this.radio;
      this.currentRow.reason = this.reason;
      updateModule(this.currentRow).then((response) => {
        this.$modal.msgSuccess("审核成功");
        this.dialogVisible = false;
        this.getList();
      });
    },
    handleUnuse(row) {
      row.moduleStatus = 4;
      updateModule(row).then((response) => {
        console.log(response, "response");
        this.$modal.msgSuccess("下架成功");

        this.getList();
      });
    },

    judgeStatus(e) {
      console.log(e, "moduleStatus");
      let statusName = "";
      switch (e) {
        case "0":
          statusName = "待审核";
          break;
        case "1":
          statusName = "已退回";
          break;
        case "2":
          statusName = "待发布";
          break;
        case "3":
          statusName = "正常";
          break;
        case "4":
          statusName = "下架";
          break;
      }
      console.log(statusName);
      return statusName;
    },

    showSupplier() {
      if (this.$store.state.user.roles.includes("admin")) {
        return true;
      } else {
        this.form.supplierId = this.$store.state.user.compId;
        return false;
      }
    },
    changeModuleTag(e) {
      switch (e) {
        case "1":
          console.log("first");
          this.nameForModule = "产品名称";
          break;
        case "2":
          this.nameForModule = "方案名称";
          break;
        case "3":
          this.nameForModule = "案例名称";
          break;
      }
      console.log(this.nameForModule);
    },
    /** 查询模块列表 */
    getList() {
      this.loading = true;
      listModule(this.queryParams).then((response) => {
        this.moduleList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log(this.moduleList, "this.moduleList");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        moduleId: undefined,
        moduleName: undefined,
        moduleTag: "1",
        moduleTypeId: undefined,
        moduleContent: undefined,
        status: "0",
        orderNum: 1,
      };
      this.moduleTypeOptions = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.moduleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.nameForModule = "产品名称";
      this.open = true;
      this.title = "添加";
      listDept({
        deptTag: 1,
      }).then((response) => {
        this.supplierOptions = this.handleTree(response.data, "deptId");
      });
      treeselectbyId().then((response) => {
        this.moduleTypeOptions = response.data;
      });
      console.log(this.moduleTypeOptions);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const moduleId = row.moduleId || this.ids;
      listDept({
        deptTag: 1,
      }).then((response) => {
        this.supplierOptions = this.handleTree(response.data, "typeId");
      });
      treeselectbyId().then((response) => {
        this.moduleTypeOptions = response.data;
      });
      this.$nextTick(() => {
        getModule(moduleId).then((response) => {
          this.form = response.data;
          this.open = true;
          this.title = "修改模块";
        });
      });
    },
    toProduct(e) {
      this.$router.push("/prod/" + e);
      console.log(e);
    },
    toCompany(e) {
      console.log(e);
      this.$router.push("/comp/" + e);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.moduleId != undefined) {
            updateModule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.moduleTypeId =
              this.form.moduleTypeId[this.form.moduleTypeId.length - 1];
            this.form.moduleStatus = 0;
            addModule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const moduleIds = row.moduleId || this.ids;
      this.$modal
        .confirm('是否确认删除模块编号为"' + moduleIds + '"的数据项？')
        .then(function () {
          return delModule(moduleIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children,
      };
    },
  },
};
</script>
